package com.stud.common.utils;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>Title: EAP</p>
 *
 * <p>Description:赵威工具类</p>
 *
 * <p>Copyright: Copyright (c) SIMPLEFAIR 2019</p>
 *
 * <p>Company: SIMPLEFAIR</p>
 *
 * @author Stud
 * @version 1.0
 * @date 2019-9-3
 */
public class ListSplitUtil {
    /**
     * 拆分数组
     *
     * @param ary 要拆分的数组
     * @param len 拆分后每个新数组的长度
     * @return
     */
    public static <T> List<T[]> spilt(T[] ary, int len) {
        if (len < 1) {
            return null;
        }
        if (Objects.isNull(ary)) {
            return null;
        }
        List<T[]> list = new ArrayList<T[]>();

        int aryLen = ary.length;

        if (aryLen <= len) {
            list.add(ary);
            return list;
        }

        int aryIndex = 0;
        int foreachIndex = 1;
        T[] tempAry = (T[]) Array.newInstance(ary[0].getClass(), len);
        list.add(tempAry);
        for (T temp : ary) {
            if (aryIndex == len) {
                int leftLen = aryLen - len * foreachIndex;
                int tempLen = leftLen > len ? len : leftLen;
                tempAry = (T[]) Array.newInstance(ary[0].getClass(), tempLen);
                list.add(tempAry);
                foreachIndex++;
                aryIndex = 0;
            }
            tempAry[aryIndex] = temp;
            aryIndex++;
        }
        return list;
    }

    /**
     * 拆分数组
     *
     * @param dataList 要拆分的集合
     * @param len      拆分后每个新数组的长度
     * @return
     */
    public static <T> List<List<T>> spilt(List<T> dataList, int len) {
        if (CollectionUtils.isEmpty(dataList)) {
            return Collections.singletonList(dataList);
        }
        if (len < 1) {
            return Collections.singletonList(dataList);
        }

        List<List<T>> list = new ArrayList<>();

        if (dataList.size() <= len) {
            list.add(dataList);
            return list;
        }

        int aryIndex = 0;
        List<T> tempList = Lists.newArrayListWithCapacity(len);
        list.add(tempList);
        for (T temp : dataList) {
            if (aryIndex == len) {
                aryIndex = 0;
                tempList = new ArrayList<>();
                list.add(tempList);
            }
            tempList.add(temp);
            aryIndex++;
        }
        return list;
    }

    /**
     * 数组转List
     *
     * @param ary
     * @return
     */
    public <T> List<T> ary2List(T[] ary) {
        List<T> list = new ArrayList<T>();
        Collections.addAll(list, ary);
        return list;
    }

}
